package com.qingke.beSuper2.command.impl;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.qingke.beSuper2.BeSuperApplication;
import com.qingke.beSuper2.BeSuperDao;
import com.qingke.beSuper2.command.SystemCommand;
import com.qingke.beSuper2.pojo.Player;
import com.qingke.beSuper2.utils.QingkeConsole;

public class SignupCommand extends SystemCommand {

	@Override
	public void execute() {
		
		BeSuperDao dao = new BeSuperDao();
		
		String username = QingkeConsole.askUserInput("Please enter your username: ");
		while (dao.isUsernameExists(username)) {
			QingkeConsole.println("username has been exist!");
			username = QingkeConsole.askUserInput("Please enter your username: ");
		}
		
		String password = QingkeConsole.askUserInput("Please enter your password: ");
		while (!validatePassword(password)) {
			password = QingkeConsole.askUserInput("Please enter your password: ");
		}
		
		String name = QingkeConsole.askUserInput("Please enter your name: ");
		Player player = dao.signup(username, password, name);
		BeSuperApplication.getInstance().setPlayerProfile(player);
	}

	private boolean validatePassword(String password) {
		// length < 6
		if (password.trim().length() < 6) {
			QingkeConsole.println("password need at least 6 characters!");
			return false;
		}
		
		// all letters
		Pattern numPattern = Pattern.compile("[0-9]");
		Matcher numMatcher = numPattern.matcher(password.trim());
		if (!numMatcher.find()) {
			QingkeConsole.println("password can't be all letters!");
			return  false;
		}
		
		// all numbers
		Pattern letterPattern = Pattern.compile("[A-Za-z]");
		Matcher letterMatcher = letterPattern.matcher(password.trim());
		if (!letterMatcher.find()) {
			QingkeConsole.println("password can't be all numbers!");
			return  false;
		}
		
		return true;
	}
	
}
